import Taro from '@tarojs/taro';
import React, { useState, useEffect } from 'react';
import { View, Text, Image, ScrollView, TouchableOpacity } from '@tarojs/components';
import { MaterialIcons } from 'taro-icons';
import './index.scss';

// 预约类型定义
interface Appointment {
  id: number;
  studentId: number;
  studentName: string;
  studentAvatar: string;
  courseType: string;
  appointmentTime: string;
  duration: number; // 时长（小时）
  status: 'pending' | 'confirmed' | 'completed' | 'cancelled';
  location: string;
  notes?: string;
  createTime: string;
}

const AppointmentManagementPage: React.FC = () => {
  const [appointments, setAppointments] = useState<Appointment[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'pending' | 'confirmed' | 'completed' | 'cancelled'>('pending');

  useEffect(() => {
    // 设置页面标题
    Taro.setNavigationBarTitle({ title: '预约管理' });
    // 加载预约数据
    loadAppointmentData();
  }, []);

  const loadAppointmentData = async () => {
    try {
      setIsLoading(true);
      // 模拟API调用
      // const response = await getAppointmentsApi();
      
      // 模拟数据
      const mockAppointments: Appointment[] = [
        {
          id: 1,
          studentId: 101,
          studentName: '张三',
          studentAvatar: 'https://via.placeholder.com/40x40',
          courseType: 'C1手动挡',
          appointmentTime: '2024-01-21 10:00:00',
          duration: 2,
          status: 'pending',
          location: '东区训练场A区',
          notes: '希望练习科目二倒车入库',
          createTime: '2024-01-20 16:30:00'
        },
        {
          id: 2,
          studentId: 102,
          studentName: '李四',
          studentAvatar: 'https://via.placeholder.com/40x40',
          courseType: 'C2自动挡',
          appointmentTime: '2024-01-21 14:00:00',
          duration: 2,
          status: 'confirmed',
          location: '东区训练场B区',
          createTime: '2024-01-19 10:20:00'
        },
        {
          id: 3,
          studentId: 103,
          studentName: '王五',
          studentAvatar: 'https://via.placeholder.com/40x40',
          courseType: 'C1手动挡',
          appointmentTime: '2024-01-20 09:00:00',
          duration: 1,
          status: 'completed',
          location: '西区训练场C区',
          createTime: '2024-01-18 18:45:00'
        },
        {
          id: 4,
          studentId: 104,
          studentName: '赵六',
          studentAvatar: 'https://via.placeholder.com/40x40',
          courseType: 'C2自动挡',
          appointmentTime: '2024-01-20 16:00:00',
          duration: 2,
          status: 'cancelled',
          location: '西区训练场B区',
          notes: '临时有事，无法参加',
          createTime: '2024-01-17 14:30:00'
        },
        {
          id: 5,
          studentId: 105,
          studentName: '陈七',
          studentAvatar: 'https://via.placeholder.com/40x40',
          courseType: 'C1手动挡',
          appointmentTime: '2024-01-22 11:00:00',
          duration: 2,
          status: 'pending',
          location: '东区训练场A区',
          createTime: '2024-01-20 09:15:00'
        }
      ];
      
      setAppointments(mockAppointments);
    } catch (error) {
      console.error('加载预约数据失败:', error);
      Taro.showToast({
        title: '数据加载失败，请重试',
        icon: 'none'
      });
    } finally {
      setIsLoading(false);
    }
  };

  const handleConfirmAppointment = async (appointment: Appointment) => {
    Taro.showModal({
      title: '确认预约',
      content: `确定要确认${appointment.studentName}的预约吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            Taro.showLoading({ title: '处理中...' });
            
            // 模拟API调用
            // await confirmAppointmentApi(appointment.id);
            
            // 更新本地数据
            setAppointments(prevAppointments => 
              prevAppointments.map(item => 
                item.id === appointment.id ? { ...item, status: 'confirmed' } : item
              )
            );
            
            Taro.hideLoading();
            Taro.showToast({
              title: '预约已确认',
              icon: 'success'
            });
          } catch (error) {
            console.error('确认预约失败:', error);
            Taro.hideLoading();
            Taro.showToast({
              title: '操作失败，请重试',
              icon: 'none'
            });
          }
        }
      }
    });
  };

  const handleCancelAppointment = async (appointment: Appointment) => {
    Taro.showModal({
      title: '取消预约',
      content: `确定要取消${appointment.studentName}的预约吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            Taro.showLoading({ title: '处理中...' });
            
            // 模拟API调用
            // await cancelAppointmentApi(appointment.id);
            
            // 更新本地数据
            setAppointments(prevAppointments => 
              prevAppointments.map(item => 
                item.id === appointment.id ? { ...item, status: 'cancelled' } : item
              )
            );
            
            Taro.hideLoading();
            Taro.showToast({
              title: '预约已取消',
              icon: 'success'
            });
          } catch (error) {
            console.error('取消预约失败:', error);
            Taro.hideLoading();
            Taro.showToast({
              title: '操作失败，请重试',
              icon: 'none'
            });
          }
        }
      }
    });
  };

  const handleCompleteAppointment = async (appointment: Appointment) => {
    Taro.showModal({
      title: '标记完成',
      content: `确定要将${appointment.studentName}的预约标记为已完成吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            Taro.showLoading({ title: '处理中...' });
            
            // 模拟API调用
            // await completeAppointmentApi(appointment.id);
            
            // 更新本地数据
            setAppointments(prevAppointments => 
              prevAppointments.map(item => 
                item.id === appointment.id ? { ...item, status: 'completed' } : item
              )
            );
            
            Taro.hideLoading();
            Taro.showToast({
              title: '已标记为完成',
              icon: 'success'
            });
          } catch (error) {
            console.error('标记完成失败:', error);
            Taro.hideLoading();
            Taro.showToast({
              title: '操作失败，请重试',
              icon: 'none'
            });
          }
        }
      }
    });
  };

  const handleStudentDetail = (studentId: number) => {
    Taro.navigateTo({
      url: `/pages/student-detail/index?id=${studentId}`
    });
  };

  const getStatusText = (status: string) => {
    const statusMap: { [key: string]: string } = {
      'pending': '待确认',
      'confirmed': '已确认',
      'completed': '已完成',
      'cancelled': '已取消'
    };
    return statusMap[status] || status;
  };

  const getStatusColor = (status: string) => {
    const colorMap: { [key: string]: string } = {
      'pending': '#faad14',
      'confirmed': '#1890ff',
      'completed': '#52c41a',
      'cancelled': '#8c8c8c'
    };
    return colorMap[status] || '#666';
  };

  const formatDateTime = (dateTimeStr: string) => {
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const filteredAppointments = appointments
    .filter(appointment => appointment.status === activeTab)
    .sort((a, b) => new Date(b.createTime).getTime() - new Date(a.createTime).getTime());

  return (
    <View className="appointment-management-page">
      {/* 标签栏 */}
      <View className="tab-bar">
        <ScrollView scrollX showsHorizontalScrollIndicator={false}>
          <TouchableOpacity 
            className={`tab ${activeTab === 'pending' ? 'active' : ''}`}
            onPress={() => setActiveTab('pending')}
          >
            <Text className="tab-text">待确认</Text>
            {appointments.filter(app => app.status === 'pending').length > 0 && (
              <View className="badge">
                <Text className="badge-text">
                  {appointments.filter(app => app.status === 'pending').length}
                </Text>
              </View>
            )}
          </TouchableOpacity>
          <TouchableOpacity 
            className={`tab ${activeTab === 'confirmed' ? 'active' : ''}`}
            onPress={() => setActiveTab('confirmed')}
          >
            <Text className="tab-text">已确认</Text>
          </TouchableOpacity>
          <TouchableOpacity 
            className={`tab ${activeTab === 'completed' ? 'active' : ''}`}
            onPress={() => setActiveTab('completed')}
          >
            <Text className="tab-text">已完成</Text>
          </TouchableOpacity>
          <TouchableOpacity 
            className={`tab ${activeTab === 'cancelled' ? 'active' : ''}`}
            onPress={() => setActiveTab('cancelled')}
          >
            <Text className="tab-text">已取消</Text>
          </TouchableOpacity>
        </ScrollView>
      </View>

      {/* 预约列表 */}
      {isLoading ? (
        <View className="loading-container">
          <Text>加载中...</Text>
        </View>
      ) : (
        <ScrollView className="appointment-scroll">
          {filteredAppointments.length > 0 ? (
            filteredAppointments.map(appointment => (
              <View key={appointment.id} className="appointment-item">
                <View className="appointment-header">
                  <TouchableOpacity 
                    className="student-info"
                    onPress={() => handleStudentDetail(appointment.studentId)}
                  >
                    <Image 
                      className="student-avatar" 
                      src={appointment.studentAvatar} 
                      mode="aspectFill"
                    />
                    <View className="student-details">
                      <Text className="student-name">{appointment.studentName}</Text>
                      <View className="course-status">
                        <Text className="course-type">{appointment.courseType}</Text>
                        <View 
                          className="status-badge"
                          style={{ backgroundColor: getStatusColor(appointment.status) }}
                        >
                          <Text className="status-text">{getStatusText(appointment.status)}</Text>
                        </View>
                      </View>
                    </View>
                  </TouchableOpacity>
                </View>
                
                <View className="appointment-content">
                  <View className="info-item">
                    <MaterialIcons name="event" size={18} color="#666" />
                    <Text className="info-label">预约时间：</Text>
                    <Text className="info-value">{formatDateTime(appointment.appointmentTime)}</Text>
                  </View>
                  <View className="info-item">
                    <MaterialIcons name="access-time" size={18} color="#666" />
                    <Text className="info-label">时长：</Text>
                    <Text className="info-value">{appointment.duration}小时</Text>
                  </View>
                  <View className="info-item">
                    <MaterialIcons name="location-on" size={18} color="#666" />
                    <Text className="info-label">训练场地：</Text>
                    <Text className="info-value">{appointment.location}</Text>
                  </View>
                  {appointment.notes && (
                    <View className="info-item notes-item">
                      <MaterialIcons name="note" size={18} color="#666" />
                      <Text className="info-label">备注：</Text>
                      <Text className="info-value notes-value">{appointment.notes}</Text>
                    </View>
                  )}
                </View>

                {/* 操作按钮 */}
                <View className="action-buttons">
                  {appointment.status === 'pending' && (
                    <>
                      <TouchableOpacity 
                        className="reject-btn"
                        onPress={() => handleCancelAppointment(appointment)}
                      >
                        <Text className="reject-btn-text">拒绝</Text>
                      </TouchableOpacity>
                      <TouchableOpacity 
                        className="accept-btn"
                        onPress={() => handleConfirmAppointment(appointment)}
                      >
                        <Text className="accept-btn-text">确认</Text>
                      </TouchableOpacity>
                    </>
                  )}
                  {appointment.status === 'confirmed' && (
                    <>
                      <TouchableOpacity 
                        className="cancel-btn"
                        onPress={() => handleCancelAppointment(appointment)}
                      >
                        <Text className="cancel-btn-text">取消预约</Text>
                      </TouchableOpacity>
                      <TouchableOpacity 
                        className="complete-btn"
                        onPress={() => handleCompleteAppointment(appointment)}
                      >
                        <Text className="complete-btn-text">标记完成</Text>
                      </TouchableOpacity>
                    </>
                  )}
                </View>
              </View>
            ))
          ) : (
            <View className="empty-container">
              <MaterialIcons name="event-note" size={80} color="#ccc" />
              <Text className="empty-text">暂无预约记录</Text>
            </View>
          )}
        </ScrollView>
      )}
    </View>
  );
};

export default AppointmentManagementPage;